#include "mainwindow.h"
#include "ui_mainwindow.h"
#include <QFileDialog>
#include <QStandardPaths>
#include <QDebug>
#include <QPainter>
#include <QProgressDialog>

MainWindow::MainWindow(QWidget *parent) :
    QMainWindow(parent),
    ui(new Ui::MainWindow)
{
    ui->setupUi(this);

    number_filename = "./pics";
    output_path = "./pics";
    logo_filename = "./pics";

    url = "http://www.xiaoantech.com/";

    ui->textEdit->setReadOnly(true);
    ui->url_lineEdit->setText("18420000000000***");
    renders = new TcQrencode();
}

MainWindow::~MainWindow()
{
    delete ui;
}

QPixmap text2Pixmap(QString text)
{
    QFont m_font(text, 60, QFont::Black);
    m_font.setFamily("黑体");
    m_font.setPointSize(80);
    m_font.setLetterSpacing(QFont::PercentageSpacing, 130);
    QFontMetrics fmt(m_font);

    //QPixmap result(fmt.horizontalAdvance(text), fmt.height());
    QPixmap result(fmt.width(text), fmt.height());

    //QRect rect(0,0,fmt.horizontalAdvance(text), fmt.height());
    QRect rect(0,0,fmt.width(text), fmt.height());
    result.fill(Qt::transparent);
    QPainter painter(&result);
    painter.setFont(m_font);

    QPen pen = QPen(Qt::black, 10);
    painter.setPen(pen);
    result.fill(Qt::white);
    //painter.drawText(const QRectF(fmt.width(text), fmt.height()),Qt::AlignLeft, text);

    painter.drawText((const QRectF)(rect), text);

    //两边留白
    QPixmap res(result.width() + 20, result.height());
    res.fill(Qt::white);
    QPainter resPainter(&res);
    resPainter.drawPixmap((res.width() - result.width()) / 2, 0, result);

    return res.scaled(800, 140, Qt::IgnoreAspectRatio, Qt::SmoothTransformation);
}

QPixmap splice_pixmap(QPixmap qrcode, QPixmap number)
{

    QPixmap temp(800, qrcode.height() + number.height());
    temp.fill(Qt::white);
    QPainter tempPainter(&temp);

    tempPainter.drawPixmap(0, 0, qrcode);
    tempPainter.drawPixmap(0, qrcode.height(), number);

     //留白
    QPixmap ret(temp.width() + 50, temp.height() + 50);
    ret.fill(Qt::white);
    QPainter retPainter(&ret);
    retPainter.drawPixmap(25, 25, temp);

    return ret;
}

//添加logo
QPixmap MainWindow::qrcode_add_logo(QPixmap qrcode)
{
    QImage logo(ui->logo_file_lineEdit->text());
    QPixmap pix_logo = QPixmap::fromImage(logo);
    int logo_w = qrcode.width() / 20 * 7;
    int logo_h = qrcode.height() / 20 * 7;
    pix_logo = pix_logo.scaled(logo_w, logo_h, Qt::IgnoreAspectRatio, Qt::SmoothTransformation);

    //计算起点
    int logo_x = (qrcode.width() / 2) - (pix_logo.width() / 2);
    int logo_y = (qrcode.width() / 2) - (pix_logo.width() / 2);

    QPainter qrPainter(&qrcode);
    qrPainter.drawPixmap(logo_x, logo_y, pix_logo);
    return qrcode;
}

uint8_t AnalyseHEX(QString line)
{
  uint8_t data;
  int cc=0;
  QString byte;
  bool ok = false;
  for(int i = 1; i < line.length(); i+=2)
  {
        byte.clear();
        byte += line.at(i);
        byte += line.at(i+1);
        data = byte.toInt(&ok, 16);
        cc += data;
  }
  cc%=256;
  cc=0x100-cc;
  return cc;
#if 0
  do
  {
      temp[0] = hex[i++];
      temp[1] = hex[i++];
      sscanf(temp,"%x",&data);

      cc += data;
  } while (i<(len-2));
  cc%=256;
  cc=0x100-cc;
  temp[0] = hex[i++];
  temp[1] = hex[i++];
  sscanf(temp,"%x",&data);
  return (cc==data)?1:0;
#endif
}

//输出按钮
void MainWindow::on_pushButton_clicked()
{
    QFile file(ui->number_file_lineEdit->text());
    if(!file.open(QIODevice::ReadOnly))
    {
        qDebug() << file.errorString();
        return;
    }

    QTextStream * out = new QTextStream(&file);//文本流
    QStringList tempOption = out->readAll().split("\n", QString::SkipEmptyParts);//每行以\n区分

    //url处理


    QProgressDialog *progress = new QProgressDialog(NULL, "取消", 0, tempOption.count(), this);
    progress->setWindowModality(Qt::WindowModal);

    progress->setWindowTitle(tr("生成进度"));
    progress->setMinimumSize(400, 50);
    progress->setMinimumDuration(1);
    progress->show();

    for(int i = 0; i < tempOption.count(); i++)
    {
        QStringList tempbar = tempOption.at(i).split("\r", QString::SkipEmptyParts);//一行中的单元格以，区分
        QString number = tempbar.at(0);

        url = ui->url_lineEdit->text().replace("***", number);
         qDebug() << "url:" << url;

         QFile bin_file(output_path+"/"+number+".hex");
         bin_file.open(QIODevice::WriteOnly);
         bin_file.seek(0);
         QTextStream stream(&bin_file);
         stream << QString(":020000040808EA\r\n");
         int addr = 0x480;
        //生成二维码
        QImage a = renders->encodeImage(url, 3);
        //a.save(output_path + "/" + number + ".bmp", "BMP");
        QPixmap src(QPixmap::fromImage(a));
        src.save(output_path + "/" + number + "_src.bmp", "BMP");
        QImage  qrcode = a.scaled(64, 64, Qt::IgnoreAspectRatio, Qt::SmoothTransformation);
        qDebug() << "format:" << qrcode.format();
        uchar*    imagebits_32 = qrcode.bits();
        qDebug("[%d X %d]\r\n", qrcode.height(), qrcode.width());
        QString line_bin;
        uint8_t line[8] = {0};
        for(int i=0; i<qrcode.height(); ++i) {
            int lineNum_32 = i * qrcode.width() * 4;
            for(int j=0; j< qrcode.width(); ++j) {
                int r_32 = imagebits_32[ lineNum_32 + j * 4 + 2];
                int g_32 = imagebits_32[ lineNum_32 + j * 4 + 1];
                int b_32 = imagebits_32[ lineNum_32 + j * 4];
                //qDebug() << "rgb:" << r_32 << g_32 << b_32;
                int index = j / 8;
                int bit_i = j % 8;

                if(r_32 > 127 && g_32 > 127 && b_32 > 127) {
                     //line[index] = line[index] | (1<<bit_i);
                    line_bin += "0";
                }
                else {
                   line_bin += "1";
                   line[index] = line[index] | (1<<bit_i);
                }

                bit_i++;
            }

            //qDebug() << line_bin;
            line_bin.clear();
            //qDebug() << "index:"<< index << bit_i;
            //qDebug("{%02x %02x %02x %02x %02x %02x %02x %02x}", line[0],line[1],line[2],line[3],line[4],line[5],line[6],line[7]);
            QString line_str = QString(":08%1").arg(addr, 4, 16, QLatin1Char('0'));
            addr+=8;
            line_str+="00";
            line_str += QString::asprintf("%02X%02X%02X%02X%02X%02X%02X%02X", line[0],line[1],line[2],line[3],line[4],line[5],line[6],line[7]);
            stream <<  line_str ;//<< QString::asprintf("%02X\r\n", );
            stream << QString::asprintf("%02X\r\n", AnalyseHEX(line_str));
            memset(line, 0, sizeof(line));

            //stream << line[0] << line[1] << line[2] << line[3] << line[4] << line[5] << line[6] << line[7];
            //qDebug() <<  hex << line[0] << line[1] << line[3] << line[4] << line[5] << line[6] << line[7];
        }
        //qDebug() << tr("qrcode[%1 * %2]").arg(qrcode.width()).arg(qrcode.height());
        {
            QString line_str = QString(":08%1").arg(0x680, 4, 16, QLatin1Char('0'));
            line_str+="00";
            line_str += QString::asprintf("%02X%02X%02X%02X%02X%02X%02X%02X", 0x17,0x00,0x01,0x00,0x00,0x00,0x00,0x00);
            stream <<  line_str;
            stream << QString::asprintf("%02X\r\n", AnalyseHEX(line_str));
        }
        {
            QString line_str = QString(":04%1").arg(0x7FC, 4, 16, QLatin1Char('0'));
            line_str+="00";
            qDebug() << url.right(8);
            line_str += url.right(8);
            stream <<  line_str;
            stream << QString::asprintf("%02X\r\n", AnalyseHEX(line_str));
        }
        QPixmap completed(QPixmap::fromImage(qrcode));
#if 0
         QPixmap qrcode_logo(QPixmap::fromImage(qrcode));


        //添加logo
        if(!(ui->logo_file_lineEdit->text().isNull()))
        {
            qrcode_logo = qrcode_add_logo(QPixmap::fromImage(qrcode));
        }

        //字符串图片
        QPixmap numPixmap = text2Pixmap(number);
        //qDebug() << tr("numPixmap[%1 * %2]").arg(numPixmap.width()).arg(numPixmap.height());

        //拼接
        QPixmap completed = splice_pixmap(qrcode_logo, numPixmap);
#endif
        //ui->label_2->setPixmap((completed));
        //completed.save(output_path + "/" + number + ".jpg", "JPG", 100);
        completed.save(output_path + "/" + number + ".bmp", "BMP", 100);
        stream << ":00000001FF";
        bin_file.close();
        progress->setValue(i);
        if(progress->wasCanceled())
        {
            break;
        }
    }

    progress->deleteLater();
    progress = NULL;

}

//导入编号列表文件
void MainWindow::on_pushButton_2_clicked()
{
    QString filename = QFileDialog::getOpenFileName(this,
                                                    tr("选择文件"),
                                                    number_filename,
                                                    tr("csv文件(*.csv);;"
                                                       "本本文件(*.txt);;"
                                                       "全部(*.*)"));
    if(!filename.isNull())
    {
        ui->number_file_lineEdit->setText(filename);
        number_filename = filename;
    }
}

//选择输出目录
void MainWindow::on_pushButton_3_clicked()
{
    QString dirpath = QFileDialog::getExistingDirectory(this,
                                                    "选择目录",
                                                    output_path,
                                                    QFileDialog::ShowDirsOnly);
    if(!dirpath.isNull())
    {
        ui->output_lineEdit->setText(dirpath);
        output_path = dirpath;
    }
}

//选择logo
void MainWindow::on_pushButton_4_clicked()
{
    QString filename = QFileDialog::getOpenFileName(this,
                                                    tr("选择文件"),
                                                    logo_filename,
                                                    tr("全部(*.*)"));
    if(!filename.isNull())
    {
        ui->logo_file_lineEdit->setText(filename);
        logo_filename = filename;
    }
}

